var http = require('http');
var url = require('url');
var items = [];

//CRUD POST,GET,DEL,PUT处理
var httpProcessor = {
    post:function(req,res){
        var item = '';
        req.setEncoding('utf8');
        req.on('data', function (chunk) {
            item += chunk;
        });
        req.on('end', function () {
            items.push(item);
            res.end('OK\n');
        });
    },
    get:function(req,res){
        var body = items.map(function(item,i){
            return i+') '+item;
        }).join('\n');
        res.setHeader('Content-Length',Buffer.byteLength(body));
        res.setHeader('Content-Type','text/plain; charset="utf-8"');
        res.end(body);
    },
    del:function(req,res){
        var path = url.parse(req.url).pathname;
        var i = parseInt(path.slice(1),10);
        if(isNaN(i)){
            res.statusCode = 400;
            res.end('Invalid item id');
        }else if(!items[i]){
            res.statusCode = 404;
            res.end('Item not found');
        }else{
            items.splice(i,1);
            res.end('OK\n');
        }
    },
    put:function(req,res){
        var val = '';
        req.setEncoding('utf8');
        req.on('data', function (chunk) {
            val += chunk;
        });
        req.on('end', function () {
            console.log(val);
            var path = url.parse(req.url).pathname;
            var i = parseInt(path.slice(1), 10);
            if (isNaN(i)) {
                res.statusCode = 400;
                res.end('Invalid item id');
            } else if (!items[i]) {
                res.statusCode = 404;
                res.end('Item not found');
            } else {
                items[i] = val;
                res.end('OK\n');
            }
        });
        
    }
}

var server = http.createServer(function(req,res){
    switch (req.method) {
        case 'POST':
            httpProcessor.post(req,res);
            break;
        case 'GET':
            // items.forEach(function(item,i){
            //     res.write(i+') '+item+'\n');
            // });
            // res.end();

            httpProcessor.get(req,res);
            break;
        case 'DELETE':
            httpProcessor.del(req,res);
            break;
        case 'PUT':
            httpProcessor.put(req,res);
        default:
            break;
    }
}).listen(3000);
